from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from rest_framework.routers import DefaultRouter
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView, SpectacularRedocView
from cmdb.api.audit_views import (
    SSHSessionViewSet, SSHCommandViewSet, AuditRuleViewSet,
    AuditAlertViewSet, SSHReplayViewSet
)
from rest_framework.authtoken.views import obtain_auth_token
from cmdb.views import RegisterView

@api_view(['GET'])
@permission_classes([AllowAny])
def api_root(request):
    """API根端点，用于健康检查"""
    return Response({
        'message': 'DevOps CMDB API',
        'version': '2.0.0',
        'status': 'healthy',
        'django_version': '4.2.7',
        'features': ['SSH审计', '资产管理', '自动化运维']
    })

# 创建审计API路由
audit_router = DefaultRouter()
audit_router.register(r'sessions', SSHSessionViewSet)
audit_router.register(r'commands', SSHCommandViewSet)
audit_router.register(r'rules', AuditRuleViewSet)
audit_router.register(r'alerts', AuditAlertViewSet)
audit_router.register(r'replay', SSHReplayViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', api_root, name='api_root'),  # API根端点
    path('api/token/', obtain_auth_token, name='token'),
    path('api/register/', RegisterView.as_view(), name='register'),

    path('api/', include('cmdb.urls')),
    path('api/audit/', include(audit_router.urls)),  # 审计API路由
    path('api/ansible/', include('ansible_management.urls')),  # Ansible管理API路由
    path('api/monitoring/', include('monitoring.urls')),  # 监控管理API路由
    path('api/gitlab/', include('gitlab_integration.urls')),  # GitLab集成API路由
    path('api/jenkins/', include('jenkins_integration.urls')),  # Jenkins集成API路由
    path('api/docker/', include('docker_management.urls')),  # Docker管理API路由

    # API文档
    # path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
    # path('api/docs/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
    # path('api/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),
]

if settings.DEBUG:
    from django.views.static import serve
    from django.http import HttpResponse
    import os

    def serve_media_with_headers(request, path, document_root=None, show_indexes=False):
        """自定义media文件服务，添加防缓存头"""
        response = serve(request, path, document_root, show_indexes)
        if isinstance(response, HttpResponse):
            # 添加防缓存头
            response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
            response['Pragma'] = 'no-cache'
            response['Expires'] = '0'
        return response

    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    # 使用自定义的media服务 - 同时支持/media/和/api/media/路径
    urlpatterns += [
        path('media/<path:path>', serve_media_with_headers, {
            'document_root': settings.MEDIA_ROOT,
        }),
        path('api/media/<path:path>', serve_media_with_headers, {
            'document_root': settings.MEDIA_ROOT,
        }),
    ]
